package com.yh.realm;

import com.yh.entity.User;
import com.yh.services.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Set;

public class Realm extends AuthorizingRealm {

    @Resource
    private UserServiceImpl userServiceImpl;
    /**
     * 执行授权逻辑
     *
     * @param principalCollection
     *
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //得到当前登录的用户  是认证逻辑的返回
        User user = (User) principalCollection.getPrimaryPrincipal();

        String name = user.getUsername();
        Set<String> roles = userServiceImpl.getRoles(name);
        Set<String> perms = userServiceImpl.getPerms(name);
        //给资源进行授权
        SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo();
        //添加资源授权
        sazi.addStringPermissions(perms);
        sazi.addRoles(roles);

        return sazi;
    }

    /**
     * 执行认证逻辑
     *
     * @param an
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken an) throws AuthenticationException {
        System.out.println("执行认证逻辑");


        // 判断 账号密码 用户密码令牌
        UsernamePasswordToken token = (UsernamePasswordToken) an;
        String username = token.getUsername();
        User user = userServiceImpl.getUserByName(username);
        if (user == null) {
            // 用户名不存在
            //shiro底层会抛出UnknownAccountException
            return null;
        }
        // 判断密码
        return new SimpleAuthenticationInfo(user, user.getPassword(),getName());
    }
}
